package com.fenghongzhang.day014;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Telephony;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {
    private EditText msg1;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            String s = (String) msg.obj;
            msg1.setText(s);
        }
    };
    private LocalBroadcastManager localBroadcastManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            requestPermissions(new String[]{Manifest.permission.READ_SMS},100);
        }
        msg1 = (EditText) findViewById(R.id.msg);

        //注册一个内容观察者
        ContentResolver contentResolver = getContentResolver();
        MyObserver myObserver = new MyObserver(handler,this);
        contentResolver.registerContentObserver(Telephony.Sms.CONTENT_URI,true,myObserver);












        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        MyReceiver myReceiver = new MyReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.dongzhi");
        localBroadcastManager.registerReceiver(myReceiver,intentFilter);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == 100 && grantResults[0] == PackageManager.PERMISSION_GRANTED){

        }else{

        }
    }

    public void send(View view) {

        //全局
//        Intent intent = new Intent();
//        intent.setAction("com.dongzhi");
//        sendBroadcast(intent);

        //本地
        Intent intent = new Intent();
        intent.setAction("com.dongzhi");
        localBroadcastManager.sendBroadcast(intent);
    }
}
